class Configurator:    
    
    def __init__(self, srcFile):
        from xml.dom import minidom
        self.xmldoc = minidom.parse(srcFile)
        attrs = dir(self)
        for i in attrs:
            if i.startswith('get') and i.endswith('Dict'):            
                getattr(self,i)()
            
    def _extractNodeProperties(self, propNode):
        di = {}
        props = propNode.getElementsByTagName('property')
        for prop in props:
            prop.normalize()
            key = str(prop.getAttribute('name'))
            value = str(prop.firstChild.data.strip())
            di[key] = value
        return di
    
    def getSqlConfigDict(self):
        sqlAgentNode = self.xmldoc.getElementsByTagName('sqlAgent')[0]
        sqlConfigDictNode = sqlAgentNode.getElementsByTagName('sqlConfigDict')[0]        
        self.sqlConfigDict = self._extractNodeProperties(sqlConfigDictNode)
        return self.sqlConfigDict
    def getSqlConfig(self):
        return self.sqlConfigDict
        

    def getRandomConfigDict(self):
        sqlAgentNode = self.xmldoc.getElementsByTagName('sqlAgent')[0]
        randomConfigDictNode = sqlAgentNode.getElementsByTagName('random')[0]
        self.randomConfigDict = self._extractNodeProperties(randomConfigDictNode)
        return self.randomConfigDict
    def getNeedRerandom(self):
        return self.randomConfigDict['needRerandom'] == 'True'
    def getNeedReread(self):
        return self.randomConfigDict['needReread'] == 'True'    
    def getRandomAmount(self):
        return int(self.randomConfigDict['randomAmount'])
    def getRandomRange(self):
        r = int(self.randomConfigDict['randomRange'])
        if r <=0 : r = None
        return r
    def getBaseFile(self):
        return self.randomConfigDict['baseFile']
    def getSubsetFile(self):
        return self.randomConfigDict['subsetFile']
    
    def getPreprocessConfigDict(self):
        preprocessNode = self.xmldoc.getElementsByTagName('preprocess')[0]
        self.preprocessConfigDict = self._extractNodeProperties(preprocessNode)
        return self.preprocessConfigDict
    def getStopwordsLanguage(self):
        return self.preprocessConfigDict['stopwordsLanguage']
    def getAdditionalStopwordsFilename(self):
        return self.preprocessConfigDict['additionalStopwordsFile']
    def getStemScale(self):
        return self.preprocessConfigDict['stemScale'] #
    def getTokenizerName(self):
        return self.preprocessConfigDict['tokenizerName'] #
    def getStemmerName(self):
        return self.preprocessConfigDict['stemmerName'] #
    def getNForGram(self):
        n = int(self.preprocessConfigDict['NForGram'])
        return  n           # #
    def getNeedConceptId(self):
        return self.preprocessConfigDict['needConceptId'] == 'True' # #
    def getSeparateSection(self):
        return self.preprocessConfigDict['separateSection'] == 'True' # #
    def getReplaceStrWithId(self):
        return self.preprocessConfigDict['replaceStrWithId'] == 'True' # #
    def getKeepIdOnly(self):
        return self.preprocessConfigDict['keepIdOnly'] == 'True'  
    def getBlockedSectionKeys(self):
        return self.preprocessConfigDict['blockedSectionKeys'].split(',') ###
    def getSubTextType(self):
        return self.preprocessConfigDict['subTextType'] ###

    def getIndexConfigDict(self):
        indexNode = self.xmldoc.getElementsByTagName('index')[0]
        self.indexConfigDict = self._extractNodeProperties(indexNode)
        return self.indexConfigDict
    def getFeatureMatrixFilePath(self):
        root = self.generateFileConfigDict['generateFilePathRoot']
        sample = 'sample_'+self.randomConfigDict['randomAmount']
        return "%s/%s"%(root, sample)
    def getFeatureMatrixFileName(self):
        path = self.getGenerateFilePath()        
        name = self.indexConfigDict['featureMatrixFileName']
        return '%s/%s'%(path,name)
    def getIndexMethod(self):
        return self.indexConfigDict['indexMethod'] #
    
    def getReduceDimConfigDict(self):
        reduceDimNode = self.xmldoc.getElementsByTagName('reduceDim')[0]
        self.reduceDimConfigDict = self._extractNodeProperties(reduceDimNode)
        return self.reduceDimConfigDict
    def getReduceDimMethodType(self):
        return self.reduceDimConfigDict['methodType']
    def getReduceDimMethodName(self): 
        return self.reduceDimConfigDict['methodName']
    def getFocusedClassesFilename(self):
        return self.reduceDimConfigDict['focusedClassesFile']
    def getFrequencyThreshold(self):
        ft = int(self.reduceDimConfigDict['frequencyThreshold'])
        return ft
    def getInfoGainThreshold(self):
        igt = float(self.reduceDimConfigDict['infoGainThreshold'])
        return igt
            
    def getGenerateFileConfigDict(self):
        generateFileNode = self.xmldoc.getElementsByTagName('generateFile')[0]
        self.generateFileConfigDict = self._extractNodeProperties(generateFileNode)
        return self.generateFileConfigDict    
    def getGenerateFileType(self):
        return self.generateFileConfigDict['generateFileType']
    def getGenerateFilePath(self):
        path = self.getFeatureMatrixFilePath()
        dir = '-'.join(self.getExperimentDescriptionList())
        return "%s/%s"%(path, dir)
    
    def getExperimentDescriptionList(self):
        fdl = []        
        fdl.append('Tok_%s'%self.getTokenizerName()[:4])
        fdl.append('%sGram%s'%(self.getNForGram(), self.getSubTextType()))
        fdl.append("SepaSec_%s"%self.getSeparateSection())
        fdl.append("ConId_%s"%self.getNeedConceptId())
        fdl.append('Repl_%s'%self.getReplaceStrWithId())
        fdl.append('KpIdOnly_%s'%self.getKeepIdOnly())
        fdl.append('Stem_%s_%s'%(self.getStemmerName()[:4],self.getStemScale()))
        fdl.append('Index_%s'%self.getIndexMethod()[:4])
        fdl.append('Freq_%s'%self.getFrequencyThreshold())
        fdl.append('Hidden_%s'%'_'.join(self.getBlockedSectionKeys()))
        return fdl
    
    def getDevelopmentConfigDict(self):
        evaluateNode = self.xmldoc.getElementsByTagName('development')[0]
        self.evaluateConfigDict = self._extractNodeProperties(evaluateNode)
        return self.evaluateConfigDict
    def getTestProportion(self):
        return float(self.evaluateConfigDict['testingSetProportion'])
    def getDevProportion(self):
        return float(self.evaluateConfigDict['developingSetProportion'])
    def getTrainProportion(self):
        return float(self.evaluateConfigDict['trainingSetProportion'])
        
        
if __name__ == "__main__":
    config = Configurator('../config/config.xml')
    attrs = dir(config)
    for i in attrs:
        if i.startswith('get') and i.endswith('Dict'):
            getter = getattr(config,i) 
    for i in attrs:
        if i.startswith('get'):            
            getter = getattr(config,i) 
            print "%s_[%s]_%s"%(i,type(getter()),str(getter()))
    
